package pl.ericpol.kernel.schemas;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import pl.ericpol.stubs.LampAdapterStub;

public class GeneralSchema extends Schema {
	
	private static Logger logger = LogManager.getLogger(GeneralSchema.class);

	/**
	 * Infinite loop to check all condition and execute all actions, that return from the condition
	 * 
	 */
	@Override
	public void execute() {
		while (true) {
			List<Action> allActions = new ArrayList<Action>();
			for (Condition currCondition : conditions) {
				allActions.addAll(currCondition.run());
			}
			allActions = deleteConflicts(allActions);
			for (Action action : allActions) {
				action.execute();
			}
			//****************for test only!!!!*************************
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//**********************************************************
		}
	}

	public List<Action> deleteConflicts(List<Action> allActions) {
		List<Action> rightActions = new ArrayList<Action>();
		Collections.sort(allActions);
		for (int i = allActions.size() - 1; i >= 0; i--) {
			Action currAction = allActions.get(i);
			for (int j = i - 1; j >= 0; j--) {
				if (currAction.getDevice().getId() == allActions.get(j)
						.getDevice().getId()) {
					break;
				}
				rightActions.add(currAction);
			}
		}
		return rightActions;
	}

}
